<?php

class News extends My_Controller {
	
	var $data;	// data array
	var $error = null;
	
    public function __construct() {
        parent::__construct("tinbai");
        $this->load->model("tinbai_model");
        $this->load->model("utility_model");        
    }

    public function index() {		
        
    }
    
	public function viewAddNews($alert = null){
		$this->load->library('form_validation');
		//$this->load->library('onlinelib', '', TRUE);
		$this->form_validation->set_error_delimiters('<div style="color: red;">', '</div>');
		$this->load->model('ngonngu_model');
		$this->load->model('chuyenmuc_model');
		$this->data['alert'] = $alert;		
    	$this->data['ngonngu'] = $this->ngonngu_model->dsNgonngu();
		$this->template->parse_view('main_content' , 'news/create.html' , $this->data);
        $this->template->parse_view('info_content' , 'template/info_content_create.html' , $this->data);
        // Render template
        $this->template->render();
    }
    
	public function viewEditNews($id){
    	$this->load->library('form_validation');
		//$this->load->library('onlinelib', '', TRUE);
		$this->form_validation->set_error_delimiters('<div style="color: red;">', '</div>');
    	$this->load->model('ngonngu_model');
    	$this->data['ngonngu'] = $this->ngonngu_model->dsNgonngu();
		$this->data['dt'] = $this->tinbai_model->xemtinbai($id,"all");
		foreach ($this->data['dt'] as $row);
		$this->data['chuyenmuc'] = $row['chuyenmuc'];
		$this->template->parse_view('main_content' , 'news/edit.html' , $this->data);
        $this->template->parse_view('info_content' , 'news/info_content_edit.html' , $this->data);
        // Render template
        $this->template->render();
    }
    
	public function viewAllNews($status){
		switch ($status) {
			case 'waiting':
				$status_data = array(
					'status'=>1
				);
				break;
			case 'edit':
				$status_data = array(
					'status'=>2
				);
				break;
			default:
				$status_data = array(
					'status'=>3
				);				
				break;
		}
		$this->session->set_userdata($status_data);
		$this->data = array();
		$this->template->parse_view('main_content' , 'news/table.html' , $this->data);
        // Render template
        $this->template->render();
    }      
    
    public function viewTranslateNews($id){
    	$this->data['dt'] = array(
    		'0' => array(
                'id' => $id,
                'title' => 'Tiêu đề bài viết',
                'summary' => 'Tóm tắt bài viết',
        		'content' => 'Nội dung bài viết'               
            )
    	);
    	// Parser data       
        $this->template->parse_view('main_content' , 'news/translate.html' , $this->data);
        $this->template->parse_view('info_content' , 'news/info_content_edit.html' , $this->data);			
        // Render template
        $this->template->render();
    }  

    
    public function addNews($id_mark = null,$image_thumbnail = null){
    	$this->load->library('form_validation');
		//dieu kien form
		$this->form_validation->set_rules('title_news', 'Tiêu đề bài viết', 'xss_clean|required|min_length[5]|max_length[150]');
		$this->form_validation->set_rules('summary_news', 'Nội dung tóm tắt', 'xss_clean|required|min_length[30]');
		$this->form_validation->set_rules('content_news', 'Nội dung bài viết', 'required|min_length[5]');
				
		if ($this->form_validation->run() == FALSE){
			$this->viewAddNews();
		}
		else{
			$check = 0;
			if($id_mark==null){
				$title = $this->security->xss_clean($this->input->post('title_news'));
				$id_mark = $this->utility_model->random();
				$check = 1;
				//image thumnail
				if($_FILES['userfile']['name'] == false)
					$image_thumbnail = "no_photo.jpg";
				else{		
					$data_path = $this->utility_model->doUpload('image','userfile',$this->session->userdata('userID'),'tintuc');
					$image_thumbnail = $data_path['duongdan'];
				}
			}
			else{
				$title = "translate_of_".$this->security->xss_clean($this->input->post('title_news'));
			}									
			$summary = $this->security->xss_clean($this->input->post('summary_news'));
			$cat_type = $this->security->xss_clean($this->input->post('chuyenmuc'));
			$content = $this->security->xss_clean($this->input->post('content_news'));
			//$status = $this->security->xss_clean($this->input->post('status'));
			$language = $this->security->xss_clean($this->input->post('ngonngu'));
			//echo false;
			if($this->utility_model->checkExist($title,'tieude_tinbai','tinbai')!="true")
			{	
				$alert = 'Có lỗi khi thêm tin! Nội dung tin đã tồn tại';			
				$this->viewAddNews($alert);
			}
			else{
				$id_baitao = $this->tinbai_model->taotinbai($title,$summary,$content,$cat_type,$image_thumbnail,$this->session->userdata('level'),$language,$id_mark,$this->session->userdata('userID'),$this->session->userdata('user'));			
				if($id_baitao){
					if($check==1){
						if($image_thumbnail==null||$image_thumbnail=="no_photo.jpg"||$this->error != null)	
							$alert = "Thêm tin mới thành công! Upload ảnh bị lỗi. ".$this->error;
						else 
							$alert = "Thêm tin mới thành công!";				
?>
					<script type="text/javascript">
					   alert('<?php echo $alert ?>');
					   window.location = "<?php echo base_url(); ?>news/viewAddNews";
					</script>
<?php	
				}
				else{
?>
				<script type="text/javascript">				   
				   window.location = "<?php echo base_url(); ?>news/viewEditNews/<?php echo $id_baitao?>";
				</script>
<?php		
					}
				}
				else{
?>
					<script type="text/javascript">
						alert("Có lỗi khi thêm tin!");				   
					   window.location = "<?php echo $_SERVER['HTTP_REFERER']; ?>";
					</script>
<?php 
				}
			}
		}
    }
    
    public function editNews($id){
   		$this->load->library('form_validation');
		//dieu kien form
		$this->form_validation->set_rules('title_news', 'Tiêu đề bài viết', 'xss_clean|required|min_length[5]|max_length[150]');
		$this->form_validation->set_rules('summary_news', 'Nội dung tóm tắt', 'xss_clean|required|min_length[5]');
		$this->form_validation->set_rules('content_news', 'Nội dung bài viết', 'required|min_length[5]');
				
		if ($this->form_validation->run() == FALSE){
			$this->viewEditNews($id);
		}
		else{
			//image thumnail
			if($_FILES['userfile']['name'] == false)
				$image_thumnail = "";
			else		
				$image_thumnail = $this->uploadImages('userfile');
			$title = $this->security->xss_clean($this->input->post('title_news'));
			$summary = $this->security->xss_clean($this->input->post('summary_news'));
			$cat_type = $this->security->xss_clean($this->input->post('chuyenmuc'));
			$content = $this->security->xss_clean($this->input->post('content_news'));
			//$status = $this->security->xss_clean($this->input->post('status'));
			$language = $this->security->xss_clean($this->input->post('ngonngu'));
			$result = $this->tinbai_model->suatinbai($id,$title,$summary,$content,$cat_type,$image_thumnail,$this->session->userdata('level'),$language,$this->session->userdata('userID'),$this->session->userdata('user'));
			if($result){
				if($image_thumnail!=null && $this->error!=NULL)
					$alert = "Sửa tin bài thành công! Upload ảnh bị lỗi. ".$this->error;
				else $alert = "Sửa tin bài thành công!";
?>
				<script type="text/javascript">
				   alert('<?php echo $alert ?>');
				   window.location = "<?php echo $_SERVER['HTTP_REFERER']; ?>";
				</script>
<?php	
			}
		}
    }
    
    public function delNews($id){
    	$result = $this->tinbai_model->xoa($id);
    	if($result){
?>
    		<script type="text/javascript">
			   alert('Xóa tin bài thành công!');
			   window.location = "<?php echo $_SERVER['HTTP_REFERER']; ?>";
			</script>	
<?php 
    	}
    	else{
?>
    		<script type="text/javascript">
			   alert('Có lỗi khi xóa tin!');
			   window.location = "<?php echo $_SERVER['HTTP_REFERER']; ?>";
			</script>
<?php 
    	}
    }
    
    public function showFinalNewsDataTable(){
    	$this->load->library('session');
		$aColumns = array('thumbnail_tinbai','tieude_tinbai', 'datetime_first', 'datetime_last', 'ten_nguoidung_first', 'ten_chuyenmuc','trangthai_tinbai', 'ngonngu', 'SUA', 'XOA');
		$_aColumns = array('id_tinbai','thumbnail_tinbai','tieude_tinbai', 'datetime_first', 'datetime_last', 'ten_nguoidung_first', 'ten_chuyenmuc', 'trangthai_tinbai', 'ngonngu.ngonngu');
		/* Indexed column (used for fast and accurate table cardinality) */
	    $sIndexColumn = "id_tinbai";
	
	// DB table to use
	    $sTable = 'tinbai';
	    
	    $iDisplayStart = $this->input->get_post('iDisplayStart', true);
	    $iDisplayLength = $this->input->get_post('iDisplayLength', true);
	    $iSortCol_0 = $this->input->get_post('iSortCol_0', true);
	    $iSortingCols = $this->input->get_post('iSortingCols', true);
	    $sSearch = $this->input->get_post('sSearch', true);
	    $sEcho = $this->input->get_post('sEcho', true);
		    
			 // Paging
	    if(isset($iDisplayStart) && $iDisplayLength != '-1' && $iDisplayLength != '0')
	    {
	        $this->db->limit($this->db->escape_str($iDisplayLength), $this->db->escape_str($iDisplayStart));
	    }
			// Ordering
	    if(isset($iSortCol_0))
	    {
	        for($i=0; $i<intval($iSortingCols); $i++)
	        {
	            $iSortCol = $this->input->get_post('iSortCol_'.$i, true);
	            $bSortable = $this->input->get_post('bSortable_'.intval($iSortCol), true);
	            $sSortDir = $this->input->get_post('sSortDir_'.$i, true);
	
	            if($bSortable == 'true')
	            {
	                $this->db->order_by($_aColumns[intval($this->db->escape_str($iSortCol))], $this->db->escape_str($sSortDir));
	            }
	        }
	    }
	    
		if(isset($sSearch) && !empty($sSearch))
	    {
	        for($i=0; $i<count($_aColumns); $i++)
	        {
	            $bSearchable = $this->input->get_post('bSearchable_'.$i, true);
	
	            // Individual column filtering
	            if(isset($bSearchable) && $bSearchable == 'true')
	            {
	                $this->db->or_like($_aColumns[$i], $this->db->escape_like_str($sSearch));
	            }
	        }
	    }
		// Select Data
	    $this->db->select('SQL_CALC_FOUND_ROWS '.str_replace(' , ', ' ', implode(', ', $_aColumns)), false);
	    $this->db->from('tinbai');
	    $this->db->join('ngonngu','ngonngu.id_ngonngu = tinbai.ngonngu');
	    $this->db->join('chuyenmuc','chuyenmuc.id_chuyenmuc = tinbai.chuyenmuc');
	    //echo $this->session->userdata('type');
	    switch ($this->session->userdata('status')){
	    	case 1:
	    		$this->db->where('trangthai_tinbai <=',$this->session->userdata('level'));
	    		break;
	    	case 2:
	    		$this->db->where('trangthai_tinbai',$this->session->userdata('level'));
	    		$this->db->where('chuthich <>','');
	    		break;
	    	default:
	    		$this->db->where('trangthai_tinbai',4);
	    		break;
	    }	   
	    $rResult = $this->db->get();		
		    // $rResult = $this->db->get($sTable);
		    // Data set length after filtering
	    $this->db->select('FOUND_ROWS() AS found_rows');
	    $iFilteredTotal = $this->db->get()->row()->found_rows;
		    // Total data set length
    	$iTotal = $this->db->count_all($sTable);
		    // Output
	    $output = array(
	        'sEcho' => intval($sEcho),
	        'iTotalRecords' => $iTotal,
	        'iTotalDisplayRecords' => $iFilteredTotal,
	        'aaData' => array()
	    );		
			
		$result = $rResult->result_array();	
		foreach($result as $news){
			$row = array();
			for ( $i=0 ; $i<count($aColumns) ; $i++ ){
				switch($aColumns[$i]){
					case 'trangthai_tinbai':
						$row[] = ($news[$aColumns[$i]] == 2||$news[$aColumns[$i]] == 3) ? 'Tin bài chờ duyệt' : 'Tin bài được đăng'; 
						break;
					case 'thumbnail_tinbai':
						$row[] = ($news[$aColumns[$i]]=="") ? "<img width='55'src=".base_url()."uploads/no_photo.jpg" : "<img width='55'src=".base_url()."images/news/".$news[$aColumns[$i]]." />";					
						break;									
					case 'SUA':
						$row[] = "<a href='".base_url()."news/viewEditNews/".$news['id_tinbai']."'>Sửa/Duyệt</a>";						
						break;
					case 'XOA':
						$row[] = "<a href='".base_url()."news/delNews/".$news['id_tinbai']."'>Xóa</a>";		
						break;
					default:
						$row[] = $news[$aColumns[$i]];
						break;
				}				
			}
			//print_r($output['aaData'][]);
			$output['aaData'][] = $row;
		}
		echo json_encode( $output );
    }

	public function takeUpNews($id,$status){
		$result = $this->tinbai_model->takeUpNews($id,$status+1);
		if($result){
?>
		<script type="text/javascript">
		   alert('Duyệt tin thành công');
		   window.location = '<?php echo base_url(); ?>news/viewAllNews'+'/final';
		</script>
<?php 	
		}
	}
	
	public function takeEditNews(){
		$result = $this->tinbai_model->takeEditNews($_POST['id_article']);
		if($result){
			echo "Báo sửa tin bài thành công";
		}
		else echo "Failed";
	}
}